package org.jlambda.list;

import java.util.LinkedList;

/**
 * Thread safe version of lists.  Both the declaration and the underlying LinkedList itself
 * are ThreadLocals.  This allows a list to be used across multiple threads without interaction.
 * 
 * NOTE, each ListDeclaration used (take, map etc) must be wrapped in a ListDeclaration.ts call.
 * If composed ListDeclarations do not use ts versions the results are unspecified. 
 * 
 * @author TGDTWCH1
 *
 * @param <T>
 */
public final class MemoizingListTS<T> extends MemoizingList<T> {
	
	private final ThreadLocal<ListDeclaration> decls = new ThreadLocal<ListDeclaration>();
	private final ThreadLocal<LinkedList<T> > lists = new ThreadLocal<LinkedList<T> >();
	
	//	 only from List
	public MemoizingListTS(ListDeclaration declaration){
		super(declaration);		
	}
	
	@Override
	public ListDeclaration<T> getDecl(){
		// copy if null
		ListDeclaration res = decls.get();
		if (res == null){
			res = decl.copyDeclaration(this);
			decls.set(res);			
		}
		return res;
	}
	
	@Override
	public LinkedList<T> getList(){
		// new if null
		LinkedList<T> res = lists.get();
		if (res == null){
			res = new LinkedList<T>();
			lists.set(res);
		}
		return res;
	}
	
}
